package com.secfound.soccer.server;

import java.util.Date;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.secfound.soccer.client.LoginService;
import com.secfound.soccer.server.persistence.DataPersistence;
import com.secfound.soccer.server.tools.SignURL;
import com.secfound.soccer.shared.db.Challenger;
import com.secfound.soccer.shared.exception.NotLoggedInException;

/**
 * Answers login/logout requests
 * Returns info from Datastore
 * @author alfonso.ayala
 *
 */
public class LoginServiceImpl extends RemoteServiceServlet implements LoginService {
	DataPersistence dp = new DataPersistence();
	private static final long serialVersionUID = 2791091622421463923L;
	private final UserService userService;
	
	public LoginServiceImpl() {
		this(UserServiceFactory.getUserService());
	}
	public LoginServiceImpl(UserService userService) {
		this.userService = userService;
	}
	
	@Override
	public Challenger login(String requestUri) {
		User user = userService.getCurrentUser();
		if (user == null) {
			Challenger info = new Challenger();
			info.setLoginURL(  SignURL.getLogin(userService, requestUri ) );
			info.setLogoutURL( SignURL.getLogout(userService, requestUri));
			info.setLoggedIn(false);
			return info;
		}
		Challenger info = null;
		if( user.getEmail()!=null ){
			info = dp.loadChallenger( user.getEmail() );
			if(info==null){
				info=new Challenger();
				info.setEmail(user.getEmail());
				info.setNickname(user.getNickname());
				info.setLoginURL(  SignURL.getLogin(userService, requestUri ) );
				info.setLogoutURL( SignURL.getLogout(userService, requestUri));
				info.setHits(0);
				info.setTries(0);
				info.setAverageHits(0);
				info.setPoints(0);
				info.setCreated(new Date());
				dp.storeChallenger(info);
			}
		}
		info.setEmail(user.getEmail());
		info.setNickname(user.getNickname());
		info.setLoginURL(  SignURL.getLogin(userService, requestUri ) );
		info.setLogoutURL( SignURL.getLogout(userService, requestUri));
		info.setLoggedIn(true);
		return info;
	}

	@Override
	public String logout(String requestUri)  throws NotLoggedInException{
		getThreadLocalRequest().getSession().invalidate();
		throw new NotLoggedInException("Logged out");
	}
}
